package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2023-12-27
 * Time：17:21
 */
@WebServlet("/collectionlist")
public class CollectionListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        req.setCharacterEncoding("utf8");
        List<Blog> blogList = new ArrayList<>();
        HttpSession session = req.getSession(false);
        if (session == null) {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("用户未登陆，请登录！！");
            return;
        }
        //将user属性从session中取出
        User user = (User) session.getAttribute("user");
        if (user == null) {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("用户未登陆，请登录！！");
            return;
        }

        CollectionDao collectionDao = new CollectionDao();
        BlogDao blogDao = new BlogDao();
        List<Integer> blogIdList =  collectionDao.selectcollection(user.getUserId());
        for (int i : blogIdList) {
            Blog blog = blogDao.selectOne(i);
            String content = blog.getContent();
            if (content.length()>50) {
                blog.setContent(content.substring(0,50));
            }
            blogList.add(blog);
        }

        String json = objectMapper.writeValueAsString(blogList);
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(json);
    }
}
